//package com.plian.system.service.fr.evaluation.impl;
//
//import cn.hutool.core.lang.Assert;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.itextpdf.text.pdf.AcroFields;
//import com.itextpdf.text.pdf.BaseFont;
//import com.itextpdf.text.pdf.PdfReader;
//import com.itextpdf.text.pdf.PdfStamper;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.dao.sys.file.FileDao;
//import com.plian.system.entity.fr.evaluation.AssetEvaluationApproval;
//import com.plian.system.entity.fr.evaluation.AssetEvaluationReport;
//import com.plian.system.mapper.fr.evaluation.AssetEvaluationReportMapper;
//import com.plian.system.model.CommonCode;
//import com.plian.system.model.ListResult;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.search.SearchEntity;
//import com.plian.system.mybatis.search.SearchParamEntiy;
//import com.plian.system.mybatis.search.TokenSearch;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.mybatis.support.Query;
//import com.plian.system.pdf.OutPdf;
//import com.plian.system.service.fr.evaluation.IAssetEvaluationApprovalService;
//import com.plian.system.service.fr.evaluation.IAssetEvaluationReportService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.file.FileService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.sys.orgzation.OrgzationService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.fr.evaluation.ApprovedInfoVO;
//import com.plian.system.vo.fr.evaluation.AssetEvaluationReportVO;
//import com.plian.system.wrapper.fr.evaluation.AssetEvaluationReportWrapper;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.io.FileUtils;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.flowable.ui.common.service.exception.BadRequestException;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.io.*;
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//import static com.plian.system.constant.sys.FormTypeConstant.FR_ASSET_EVALUATION_REPORT;
//import static com.plian.system.pdf.OutPdf.processDate;
//
///**
// * <p>
// * 资产评估报备表 服务实现类
// * </p>
// *
// * @author hu song
// * @since 2023-03-22 19:08:36
// */
//@Slf4j
//@Service
//@RequiredArgsConstructor
//public class AssetEvaluationReportServiceImpl extends BaseServiceImpl<AssetEvaluationReportMapper, AssetEvaluationReport> implements IAssetEvaluationReportService, BaseFlowService {
//
//    private final AssetEvaluationReportMapper assetEvaluationReportMapper;
//    private final AssetEvaluationReportWrapper assetEvaluationReportWrapper;
//    private final FormWorkflowService formWorkflowService;
//    private final IFormCodeService formCodeService;
//    private final IAssetEvaluationApprovalService assetEvaluationApprovalService;
//    private final FileDao fileDao;
//    private final FileService fileService;
//    private final IOrgService orgService;
//    private final OrgzationService orgzationService;
//
//    @Override
//    public ListResult<AssetEvaluationReportVO> findAll(Query query) {
//        ListResult<AssetEvaluationReportVO> listResult = new ListResult<>(CommonCode.SUCCESS);
//
//        List<SearchEntity> entityList = query.getSearch();
//        if (query.getAscs() == null && query.getDescs() == null) {
//            query.setDescs("create_time");
//        }
//        QueryWrapper<AssetEvaluationReport> queryWrapper = SearchParamEntiy.getQueryWrapper(
//                Condition.getQueryWrapper(new AssetEvaluationReport()), entityList
//        );
//
//        TokenSearch<AssetEvaluationReport> tokenSearch = new TokenSearch<>();
//		tokenSearch.addTokenQuery(queryWrapper, query);
//
//        IPage<AssetEvaluationReport> page = page(Condition.getPage(query), queryWrapper);
//        listResult.setList(assetEvaluationReportWrapper.entityToVO(page.getRecords()));
//        listResult.setTotal((int) page.getTotal());
//        return listResult;
//    }
//
//    @Override
//    public AssetEvaluationReportVO detail(AssetEvaluationReport assetEvaluationReport) {
//        Assert.notNull(assetEvaluationReport.getId(), "id不能为空");
//        return Optional.ofNullable(assetEvaluationReportWrapper.entityToVO(getById(assetEvaluationReport.getId()))).orElseThrow(() -> new BadRequestException("资产评估主要事项报备数据不存在"));
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean saveOrUpdate(AssetEvaluationReport entity) {
//        boolean isSaveFlag = false;
//        if (Objects.isNull(entity.getId())) {
//            isSaveFlag = true;
//            entity.setFormType(FormTypeConstant.FR_ASSET_EVALUATION_REPORT);
//            entity.setReportNumber("邢国资评报" + formCodeService.getContainBracketsFilingCode(FormTypeConstant.FR_ASSET_EVALUATION_REPORT) + "号");
//            entity.setCode(formCodeService.getCode(FormTypeConstant.FR_ASSET_EVALUATION_REPORT));
//        }
//
//        boolean result = super.saveOrUpdate(entity);
//        if (isSaveFlag && Objects.equals(entity.getFormType(), FormTypeConstant.FR_ASSET_EVALUATION_REPORT)) {
//            HashMap<String, Object> processVariable = new HashMap<>();
//            formWorkflowService.startProcessAndSimulate(String.valueOf(entity.getId()), String.valueOf(entity.getFormType()), processVariable);
//        }
//
//        return result;
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean saveAuditInfo(AssetEvaluationReport resource) {
//        Assert.notNull(resource.getId(), "id不能为空");
//        ApprovedInfoVO approvedInfoVO = resource.getApprovedInfoVO();
//        Assert.notNull(approvedInfoVO, "审批信息不能为空");
//        AssetEvaluationReport assetEvaluationReport = Optional.ofNullable(getById(resource.getId())).orElseThrow(() -> new BadRequestException("资产评估主要事项报备数据不存在"));
//        // 集团
//        if (Objects.equals(resource.getDeclareUnitId(), orgzationService.getUnitId(TokenUtil.getTokenOrgId()))) {
//            assetEvaluationReport.setDeptApprovedUser(approvedInfoVO.getApprovedUser());
//            assetEvaluationReport.setDeptApprovedOpinion(approvedInfoVO.getApprovedOpeinion());
//            assetEvaluationReport.setDeptApprovedTime(approvedInfoVO.getApprovedTime());
//            assetEvaluationReport.setDeptApprovedSignImageId(approvedInfoVO.getApprovedImageId());
//        }
//        // 国资
//        if (Objects.equals(true, orgService.checkIsGzw(TokenUtil.getTokenOrgId()))) {
//            assetEvaluationReport.setAuthorityApprovedUser(approvedInfoVO.getApprovedUser());
//            assetEvaluationReport.setAuthorityApprovedOpinion(approvedInfoVO.getApprovedOpeinion());
//            assetEvaluationReport.setAuthorityApprovedTime(approvedInfoVO.getApprovedTime());
//            assetEvaluationReport.setAuthorityApprovedSignImageId(approvedInfoVO.getApprovedImageId());
//        }
//        // 附件
//        if (CollectionUtil.isNotEmpty(resource.getDocList())) {
//            fileService.edit(String.valueOf(resource.getId()), resource.getDocList());
//        }
//        return updateById(assetEvaluationReport);
//    }
//
//    @Transactional(rollbackFor = Exception.class)
//    public Boolean handleStatus(Long id, int updateStatus) {
//        try {
//            AssetEvaluationReport assetEvaluationReport = getById(id);
//            /**
//             * 设置审批人和审批时间
//             */
//            if (updateStatus == FormStatusConstant.FINISH) {
//                assetEvaluationReport.setAuthorityApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                assetEvaluationReport.setAuthorityApprovedTime(now);
//
//            }
//            assetEvaluationReport.setStatus(updateStatus);
//            updateById(assetEvaluationReport);
//            log.info("更新[资产评估报备表]id=" + id + "状态为: " + updateStatus + "");
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED);
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        LambdaQueryWrapper<AssetEvaluationReport> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.in(AssetEvaluationReport::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//        List<AssetEvaluationReport> assetEvaluationReport = list(queryWrapper);
//        List<AssetEvaluationReportVO> assetEvaluationReportVO = assetEvaluationReportWrapper.entityToVO(assetEvaluationReport);
//        List<PageData> pageDataList = new ArrayList<>();
//        try {
//            if (CollectionUtil.isNotEmpty(assetEvaluationReportVO)) {
//                for (AssetEvaluationReportVO vo : assetEvaluationReportVO) {
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    // 集团名称
//                    pd.put("UNITNAME", vo.getDeclareUnitName());
//                    pd.put("APPLICANTNAME", vo.getCreateUserName());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getDeclareUnitId());
//                    pd.put("formType", vo.getFormType());
//                    // 企业名称
//                    pd.put("orgName", vo.getDeclareUnitName());
//                    pageDataList.add(pd);
//                }
//            }
//
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FR_ASSET_EVALUATION_REPORT);
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean deleteLogic(List<Long> ids) {
//        Optional.ofNullable(listByIds(ids)).flatMap(list -> Optional.ofNullable(assetEvaluationApprovalService.list(Wrappers.lambdaQuery(AssetEvaluationApproval.class).in(AssetEvaluationApproval::getAssetEvaluationReportId, list.stream().map(AssetEvaluationReport::getId).collect(Collectors.toList()))))).ifPresent(l -> {
//            assetEvaluationApprovalService.deleteLogic(l.stream().map(AssetEvaluationApproval::getId).collect(Collectors.toList()));
//        });
//        return super.deleteLogic(ids);
//    }
//
//    @Override
//    public File exportPdf(AssetEvaluationReport assetEvaluationReport) {
//        AssetEvaluationReportVO bean;
//        if (Objects.nonNull(assetEvaluationReport.getId())) {
//            bean = assetEvaluationReportWrapper.entityToVO(assetEvaluationReportMapper.selectById(assetEvaluationReport.getId()));
//        } else {
//            bean = assetEvaluationReportWrapper.entityToVO(assetEvaluationReport);
//        }
//        File file = null;
//
//        try {
//            InputStream inputStream = this.getClass().getResourceAsStream("/pdf/assetEvaluationReport.pdf");
//            //通过将文件转换为临时文件进行操作
//            File model = File.createTempFile("model", ".png");
//            try {
//                FileUtils.copyInputStreamToFile(inputStream, model);
//            } finally {
//                //关闭IO
//                IOUtils.closeQuietly(inputStream);
//            }
//
//            if (bean != null && model.exists()) {
//                Map<String, Object> data = OutPdf.beanToMap(bean);
//                // 评估机构选聘依据和方式
//                data.put("evaluationAgencySelectBasisAndMode", bean.getEvaluationAgencySelectBasis() + "、" + bean.getEvaluationAgencySelectMode());
//                // 图片转base64
//                try {
//                    PageData doc = fileDao.findbyId(bean.getAuthorityApprovedSignImageId());
//                    data.put("authorityApprovedSignImageStr", ImageUtils.getImageBase64(doc.getString("filePath") + File.separator + doc.getString("fileName")));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                try {
//                    PageData doc = fileDao.findbyId(bean.getDeptApprovedSignImageId());
//                    data.put("authorityApprovedSignImageStr", ImageUtils.getImageBase64(doc.getString("filePath") + File.separator + doc.getString("fileName")));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//
//                String fileName = model.getPath();
//                PdfReader reader = new PdfReader(fileName);
//                ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                /* 将要生成的目标PDF文件名称 */
//                PdfStamper ps = new PdfStamper(reader, bos);
//                /* 使用中文字体 */
//                BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//                ArrayList<BaseFont> fontList = new ArrayList<>();
//                fontList.add(bf);
//
//                /* 取出报表模板中的所有字段 */
//                AcroFields fields = ps.getAcroFields();
//                fields.setSubstitutionFonts(fontList);
//                for (String key : data.keySet()) {
//                    String value = data.get(key) == null ? null : data.get(key).toString();
//                    if (data.get(key) instanceof Date) {
//                        value = processDate((Date) data.get(key));
//                    }
//                    fields.setField(key, value);
//                }
//
//                /* 必须要调用这个，否则文档不会生成的 */
//                ps.setFormFlattening(true);
//                ps.close();
//                File dir = new File(model.getParent());
//                String classFullName = bean.getClass().getName();
//                file = File.createTempFile(classFullName.substring(classFullName.lastIndexOf(".")), ".pdf", dir);
//                OutputStream fos = new FileOutputStream(file);
//                fos.write(bos.toByteArray());
//                fos.flush();
//                fos.close();
//                bos.close();
//            }
//
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return file;
//    }
//}
